/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.travel.service;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boxin.framework.base.utils.Constants;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.dao.QRCodeDao;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.travel.dao.BusDao;
import com.boxin.ims.modules.travel.entity.Bus;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.DateUtils;

/**
 * 车辆Service
 * @author Jakemanse
 * @version 2013-07-31
 */
@Component
@Transactional(readOnly = true)
public class BusService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(BusService.class);
	
	@Autowired
	private BusDao busDao;
	
	@Autowired
	QRCodeDao QRCodeDao;
	
	public Bus get(Long id) {
		return busDao.findOne(id);
	}
	
	
	public List<Bus> find(Bus bus){
		DetachedCriteria dc = busDao.createDetachedCriteria();
		if (bus.getUser()!=null && bus.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", bus.getUser().getId()));
		}
		if (StringUtils.isNotEmpty(bus.getName())){
			dc.add(Restrictions.like("name", "%"+bus.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+bus.getRemarks()+"%"));
		}
		//dc.add(Restrictions.eq("delFlag", Bus.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return busDao.find( dc);
	}
	
	
	
	public Page<Bus> find(Page<Bus> page, Bus bus) {
		DetachedCriteria dc = busDao.createDetachedCriteria();
		if (bus.getUser()!=null && bus.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", bus.getUser().getId()));
		}
		if (StringUtils.isNotEmpty(bus.getName())){
			dc.add(Restrictions.like("name", "%"+bus.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getNumber())){
			dc.add(Restrictions.like("number", "%"+bus.getNumber()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getStartPlace())){
			dc.add(Restrictions.like("startPlace", "%"+bus.getStartPlace()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getEndPlace())){
			dc.add(Restrictions.like("endPlace", "%"+bus.getEndPlace()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getRoadLine())){
			dc.add(Restrictions.like("roadLine", "%"+bus.getRoadLine()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getDrivers())){
			dc.add(Restrictions.like("drivers", "%"+bus.getDrivers()+"%"));
		}
		if (StringUtils.isNotEmpty(bus.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+bus.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", Bus.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return busDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Bus bus) {
		
		//添加生成维码
		busDao.save(bus);
		QRCode qrCode = null;
		//生成二维码
		if(bus.getQrCode() == null || bus.getQrCode().getId() == null){
			qrCode = new QRCode();
			qrCode.setContent("None");
			qrCode.setJpegPath(Constants.getDefaultQRCodeResourcePath()+System.currentTimeMillis()+""+bus.getId());
			String con = QRCodeUtils.generateTravelBusURL(bus.getId());
			qrCode.setContent(con);
			
		}else{
			qrCode = bus.getQrCode();
			String con = QRCodeUtils.generateTravelBusURL(bus.getId());
			qrCode.setContent(con);
		}
		//QRCodeUtils.generateQRCodeWithErrorLevel("jpeg",qrCode.getContent(), qrCode.getJpegPath(), 300, 300,QRCodeUtils.ERROR_LEVEL_M);
		
		
		try {
			String viewUrl = "http://qr.liantu.com/api.php?text=" + qrCode.getContent() +"&el=h";
			File file = new File(qrCode.getJpegPath()+".jpeg");
			QRCodeUtils.downloadImg(viewUrl, file);
		} catch (Exception e) {
			QRCodeUtils.generateQRCodeWithErrorLevel("jpeg",qrCode.getContent(), qrCode.getJpegPath(), 300, 300,QRCodeUtils.ERROR_LEVEL_H);
			e.printStackTrace();
		}
		
		
		
		QRCodeDao.save(qrCode);	
		bus.setQrCode(qrCode);
		busDao.save(bus);
		
		
	}
	
	
	public String generateQRCodeNumber(){
		StringBuffer sb = new StringBuffer();
		String year = DateUtils.getDate("yyyy");
		String month = DateUtils.getDate("MM");
		String day = DateUtils.getDate("dd");
		Random random = new Random();
		int rnd = random.nextInt(99000);
		String strand = rnd+"";
		
		String newstr = strand;
		for(int i=0;i<5-strand.length();i++){
			newstr = "0"+newstr;
		}
		
		sb.append("310").append(year).append(month).append(day).append(newstr);
		return sb.toString();
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		busDao.deleteById(id);
	}
	
}
